<template>
  <div class="app-container">
    <div>
        <el-select  aria-label="服务名" size="small" @change="queryUser" v-model="IChannelViewModel.MServiceName" class="filter-item" placeholder="请选媒体服务">
             <el-option v-for="item in typeOptions" :key="item.ID" :label="item.TypeName" :value="item.TypeCode" />
        </el-select>
      <!-- <el-input v-model="IChannelViewModel.Name" placeholder="频道名称" style="width: 200px;" class="filter-item"
        @keyup.enter.native="queryUser" />
      <el-date-picker v-model="IChannelViewModel.StartTime" placeholder="开始时间" style="width: 200px;" class="filter-item"
       @keyup.enter.native="queryUser" type="datetime" value-format="yyyy-MM-dd HH:mm" />
      <el-date-picker v-model="IChannelViewModel.EndTime" placeholder="结束时间" style="width: 200px;" class="filter-item"
       @keyup.enter.native="queryUser" type="datetime" value-format="yyyy-MM-dd HH:mm" /> -->
     <el-button type="primary" size="small" @click="handleAddChannle" icon="el-icon-plus">新增频道</el-button>
      <el-button type="primary" size="small" @click="refreshUser" icon="el-icon-refresh">刷新</el-button>
    </div>
    <el-table v-loading="loading" :data="channelList" style="width: 100%;margin-top:30px;" border @sort-change="sortChange">
 <el-table-column  label="服务名" width="180" sortable="custom" prop="MServiceName">
        <template slot-scope="scope">{{ scope.row.MServiceName }}</template>
      </el-table-column>
      <el-table-column  label="频道名称" width="150" sortable="custom" prop="Name">
        <template slot-scope="scope">{{ scope.row.Name }}</template>
      </el-table-column>
       <el-table-column label="当前状态" width="120"  sortable="custom" prop="State">
        <template slot-scope="scope"><i class="el-icon-video-pause" v-if="scope.row.State == 'Stopped'"
              title="已停止"></i><i class="el-icon-video-play" v-if="scope.row.State == 'Running'"
              title="正在运行"></i>{{ scope.row.State | typeFilter}}</template>
      </el-table-column>
     <el-table-column label="直播地址" sortable="custom" prop="Url">
        <template slot-scope="scope">{{ scope.row.Url}}</template>
      </el-table-column>
      <el-table-column align="center" label="直播开关" width="120">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.IsStar" active-color="#13ce66" @change="changeStatus(scope)"
                inactive-color="#8d8d96">
              </el-switch>
            </template>
          </el-table-column>
           <el-table-column align="center" label="操作" width="120">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="handleDelete(scope)"
            icon="el-icon-delete"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
    <div class="block" style="float:right;margin-top:15px;" v-if="IChannelViewModel.total>0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="IChannelViewModel.page" :page-sizes="[10, 20, 30, 40,100]" :page-size="IChannelViewModel.pageSize"
        @prev-click="lastPage" @next-click="nextPage" background layout="total, sizes, prev, pager, next, jumper"
        :total="IChannelViewModel.total"></el-pagination>
    </div>
    <el-dialog :visible.sync="dialogVisible" :close-on-click-modal="false" :title="dialogType==='edit'?'编辑频道':'新增频道'">
      <el-form
        :model="ams"
        :rules="rules"
        ref="ams"
        label-width="80px"
        label-position="right"
        style="width: 90%;"
      >
        <el-row>
          <el-col :span="12">
             <el-form-item label="服务名" prop="MServiceName">
            <el-select    v-model="ams.MServiceName" class="filter-item" placeholder="请选媒体服务">
             <el-option v-for="item in typeOptions" :key="item.ID" :label="item.TypeName" :value="item.TypeCode" />
        </el-select>
         </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="频道名称" prop="Name">
              <el-input v-model="ams.Name" placeholder="机构名称"/>
            </el-form-item>
          </el-col>
        </el-row>



        <div style="text-align:right">
          <el-button type="danger" size="mini" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" size="mini" @click="confirmRole('ams')">确认</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

  import {GetDictionaryByPCode} from '@/api/dictionary';
  import { getIChannelList,changeChannelStatus,updateAMS,addAMS,deleteAMS } from '@/api/azruemediaservice';
  import { deepClone } from "@/utils";
  const defaultUser = {
    UId:'',
     Name: '',
      State: '',
      Url: '',
      MServiceName: '',
      IsStar:'',
      CreateTime: ''
  }
  export default {
  filters: {
      typeFilter(type) {
        const typeMap = {
          Stopped: '已停止',
          Running: '直播中'
        }
        return typeMap[type]
      }
    },
    data() {
      return {
        typeOptions: ["qdlsams", "qdlsams1"],
        IChannelViewModel: {
          page: 1,
          pageSize: 10,
          total: 0,
          Name: '',
          State: '',
          Url:'',
          IsStar:'',
          MServiceName: '',
          OrderBy: 'MServiceName',//排序字段
          IsAsc: 'true' //是否升序
        },
        dialogVisible: false,
        dialogType: '',
        ams: Object.assign({}, defaultUser),
        channelList: [],
        loading: true,
        rules:{
Name: [
          { required: true, message: "请填写频道名称", trigger: "blur" }
        ],MServiceName: [
          { required: true, message: "请选择服务", trigger: "change" }
        ]

        }
      }
    },

 computed: { // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存

    },
    created() {  // 实例创建完成后执行的代码
    this.GetDictionaryByPCode("AMS");
       this.getIChannelList(this.IChannelViewModel);

    },
    methods: {
       async GetDictionaryByPCode(ams) {
        const res = await GetDictionaryByPCode(ams);
        this.typeOptions = res.data;
        this.typeOptions.unshift({ID:'',TypeName:'全部'})
      },
      async getIChannelList(IChannelViewModel) {
        const res = await getIChannelList(IChannelViewModel);
        if (res.data) {
          this.IChannelViewModel.total = res.data.TotalCount;
        }
        this.channelList = res.data.AMSItems;
        this.loading = false;
      },

      async changeChannelStatus(sname,name, status) {
         await changeChannelStatus(sname,name, status);
        this.getIChannelList(this.IChannelViewModel);
      },
      changeStatus(scope) {
        this.changeChannelStatus(scope.row.MServiceName,scope.row.Name,scope.row.IsStar);
        this.$notify({
          message: "操作成功!",
          type: "success",
          title: "成功",
          duration: 3000
        });
      },
      queryUser() {
        this.getIChannelList(this.IChannelViewModel);
      },
       handleAddChannle() {
      this.$nextTick(() => {
        //this.$refs["ams"].clearValidate(); //清空上次的错误验证提示
      });
      this.ams = Object.assign({}, defaultUser);
      this.dialogType = "new";
      this.dialogVisible = true;
    },
     async confirmRole(formName) {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs[formName].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }
      const isEdit = this.dialogType === "edit";

      if (isEdit) {
        let r = await updateAMS(this.ams);
      } else {
        let r = await addAMS(this.ams);
        this.IChannelViewModel.page = 1;
      };

      this.getIChannelList(this.IChannelViewModel);
      this.dialogVisible = false;
      this.$notify({
          message: "添加频道成功!",
          type: "success",
          title: "成功",
          duration: 3000
        });

    },
    handleDelete({ $index, row }) {
      this.$confirm("确认删除通道?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
         var r = await deleteAMS(row.MServiceName,row.Name);
          if (r.code === 200) {
          this.$notify({
          message: r.message,
          type: "success",
          title: "成功",
          duration: 3000
        });
          this.getIChannelList(this.IChannelViewModel);
          }
        })
        .catch(err => {
          console.error(err);
        });
    },
      refreshUser() {
        this.IChannelViewModel.Name = '';
        this.IChannelViewModel.MServiceName = '';
        this.IChannelViewModel.page = 1;
        this.getIChannelList(this.IChannelViewModel);
      },
      sortChange(data) {
        const { prop, order } = data
        this.IChannelViewModel.OrderBy = prop
        if (prop == null || prop == "")
          this.IChannelViewModel.OrderBy = "Name"
        if (order === 'ascending') {
          this.IChannelViewModel.IsAsc = true
        } else {
          this.IChannelViewModel.IsAsc = false
        }
        this.queryUser()
      },
      lastPage(val) {
        this.IChannelViewModel.page = val;
      },
      nextPage(val) {
        this.IChannelViewModel.page = val;
      },
      handleSizeChange(val) {
        this.IChannelViewModel.pageSize = val;
        this.getIChannelList(this.IChannelViewModel);
      },
      handleCurrentChange(val) {
        this.IChannelViewModel.page = val
        this.getIChannelList(this.IChannelViewModel)
      }
    }
  }
</script>
